<template>
  <div class="wh100 d-flex justify-content-center align-items-center">
    <div class="box-shadow p-5 transbg rounded">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" size="small" class="login-form">
        <div class="d-flex justify-content-center mb-3">益康医疗</div>
        <el-form-item label="账号" prop="username" class="mb-2">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item class="mt-4">
          <el-button class="w-100" type="primary" @click="submitForm('ruleForm')">登 录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { userLogin } from '@/api/index'
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = {
            username: this.ruleForm.username,
            password: this.ruleForm.password
          }
          userLogin(params).then(res => {
            if (res) {
              localStorage.setItem('TOKEN', res.data.token)
              localStorage.setItem('USER_INFO', JSON.stringify(res.data.userInfo))
              this.$router.replace('/')
              this.$message.success(res.message)
            }
          })
        } else {
          this.$message.error('请输入账号密码')
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.path !== '/' && localStorage.getItem('TOKEN')) {
      next('/dashboard')
    }
    next()
  }
}
</script>

<style lang="scss" scoped>
.wh100 {
  width: 100vw;
  height: 100vh;
  background: url('@/assets/images/login-bg.jpg');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.login-form {
  width: 240px;
}

.transbg {
  background: rgba($color: #fff, $alpha: .8);
}

::v-deep .el-form-item {
  margin-bottom: 0;
}
</style>
